package com.bible.fire.local;

import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import com.bible.fire.pad.activity.surface.DesktopActivity;
import com.bible.fire.service.RestartAppService;
import com.bible.fire.util.ViewUtil;
import com.bible.fire.util.WindowUtil;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import android.os.Looper;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * 
 * @author Administrator
 *
 */
public class CrashHandler implements UncaughtExceptionHandler {
	
	private String TAG = CrashHandler.class.getSimpleName();
	
	private static CrashHandler handler = new CrashHandler();
	
	private Context mContext;
	
	private UncaughtExceptionHandler mDefaultHandler;
	
	private CrashHandler(){
		
	}
		
	public static CrashHandler getInstance(){
		return handler;
	}
	
	public void  init(Context ctx){
		mContext = ctx;
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		Thread.setDefaultUncaughtExceptionHandler( this );
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		Log.e(TAG, "crash exception", ex);
		// TODO Auto-generated method stub		
        if( !handleException( ex ) && mDefaultHandler != null ){
        	Log.d(TAG, "no handle exception");
        	mDefaultHandler.uncaughtException(thread, ex);
        }
	}
	
	private boolean handleException( Throwable e ){
		Log.d(TAG, "start to handle exception");
		if( e == null ){
			return false;
		}
		Log.d(TAG, "restart app");
        
		new Thread(){
			public void run(){
				Looper.prepare();
				Log.d(TAG, "asyn to quit app");
				//WindowUtil.showTip("程序出现bug了!");
				WindowManager wm = (WindowManager)mContext.getSystemService( Context.WINDOW_SERVICE );
				wm.addView( ViewUtil.getQuitView4Exception(mContext), WindowUtil.getCenterParams());
				/*
                 Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_LONG).show();
                   */
				
				 
				/*
				Intent intent = new Intent(mContext, RestartAppService.class );
				mContext.startService( intent );
				*/
				Looper.loop();
				//PendingIntent pending = PendingIntent.getService(mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);
				//AlarmManager aMgr = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
				//aMgr.set(AlarmManager.RTC, System.currentTimeMillis() + 200, pending);
			}
		}.start();  
		
		return true;
	}

}
